<script setup name="Tenant" lang="ts">
import { parseTime } from '../../../utils/ruoyi.ts'
import {
  addTenant,
  changeTenantStatus,
  delTenant,
  getTenant,
  listTenant,
  syncTenantPackage,
  updateTenant,
} from '@/api/system/tenant'
import { selectTenantPackage } from '@/api/system/tenantPackage'
import type { TenantForm, TenantQuery, TenantVO } from '@/api/system/tenant/types'
import type { TenantPkgVO } from '@/api/system/tenantPackage/types'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const tenantList = ref<TenantVO[]>([])
const packageList = ref<TenantPkgVO[]>([])
const buttonLoading = ref(false)
const loading = ref(true)
const message = useMessage()
const modal = useModal()
const ids = ref<Array<string | number>>([])
const total = ref(0)

const queryFormRef = ref()
const tenantFormRef = ref()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const initFormData: TenantForm = {
  id: undefined,
  tenantId: undefined,
  contactUserName: '',
  contactPhone: '',
  username: '',
  password: '',
  companyName: '',
  licenseNumber: '',
  domain: '',
  address: '',
  intro: '',
  remark: '',
  packageId: '',
  expireTime: '',
  accountCount: 0,
  status: '0',
}
const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: '',
    contactUserName: '',
    contactPhone: '',
    companyName: '',
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    tenantId: [{ required: true, message: '租户编号不能为空', trigger: 'blur' }],
    contactUserName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
    contactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
    username: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
    ],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询所有租户套餐 */
async function getTenantPackage() {
  const res = await selectTenantPackage()
  packageList.value = res.data
}

/** 查询租户列表 */
async function getList() {
  loading.value = true
  const res = await listTenant(queryParams.value)
  tenantList.value = res.rows
  total.value = res.total
  loading.value = false
}

// 租户套餐状态修改
async function handleStatusChange(row: TenantVO) {
  const text = row.status === '0' ? '启用' : '停用'
  try {
    modal.confirm({
      title: '确认操作',
      content: `确认要"${text}""${row.companyName}"租户吗?`,
      onOk: async () => {
        await changeTenantStatus(row.id, row.tenantId, row.status)
        message.success(`${text}成功`)
      },
    })
  }
  catch {
    row.status = row.status === '0' ? '1' : '0'
  }
}

// 取消按钮
function cancel() {
  reset()
  dialog.visible = false
}

// 表单重置
function reset() {
  form.value = { ...initFormData }
  tenantFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getTenantPackage()
  dialog.visible = true
  dialog.title = '添加租户'
}

/** 修改按钮操作 */
async function handleUpdate(row?: TenantVO) {
  reset()
  await getTenantPackage()
  const _id = row?.id || ids.value[0]
  const res = await getTenant(_id)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改租户'
}

/** 提交按钮 */
function submitForm() {
  tenantFormRef.value?.validate().then(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true
      if (form.value.id)
        await updateTenant(form.value).finally(() => buttonLoading.value = false)
      else
        await addTenant(form.value).finally(() => buttonLoading.value = false)

      message.success('操作成功')
      dialog.visible = false
      await getList()
    }
  })
}

/** 删除按钮操作 */
async function handleDelete(row?: TenantVO) {
  const _ids = row?.id || ids.value
  loading.value = true
  modal.confirm({
    title: '确认删除',
    content: `是否确认删除租户编号为"${_ids}"的数据项？`,
    onOk: async () => {
      await delTenant(_ids).finally(() => loading.value = false)
      await getList()
      message.success('删除成功')
    },
  })
}

/** 同步租户套餐按钮操作 */
async function handleSyncTenantPackage(row: TenantVO) {
  try {
    loading.value = true
    modal.confirm({
      title: '确认操作',
      content: `确认要同步租户套餐"${row.companyName}"吗?`,
      onOk: async () => {
        await syncTenantPackage(row.tenantId, row.packageId)
        await getList()
        message.success('同步成功')
      },
    })
  }
  catch {
    return
  }
  finally {
    loading.value = false
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('system/tenant/export', {
    ...queryParams.value,
  }, `tenant_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card class="mb-20px">
      <div class="flex flex-between">
        <div>
          <a-form ref="queryFormRef" :model="queryParams" layout="inline">
            <a-form-item label="租户编号" prop="tenantId">
              <a-input
                v-model:value="queryParams.tenantId" placeholder="请输入租户编号" clearable style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="联系人" prop="contactUserName">
              <a-input
                v-model:value="queryParams.contactUserName" placeholder="请输入联系人" clearable
                style="width: 200px" @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="联系电话" prop="contactPhone">
              <a-input
                v-model:value="queryParams.contactPhone" placeholder="请输入联系电话" clearable
                style="width: 200px" @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="企业名称" prop="companyName">
              <a-input
                v-model:value="queryParams.companyName" placeholder="请输入企业名称" clearable
                style="width: 200px" @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  搜索
                </a-button>
                <a-button @click="resetQuery">
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-row :gutter="10">
            <a-col :span="1.5">
              <a-button v-hasPermi="['system:tenant:add']" type="primary" plain @click="handleAdd">
                新增
              </a-button>
            </a-col>

            <a-col :span="1.5">
              <a-button v-hasPermi="['system:tenant:export']" @click="handleExport">
                导出
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>

    <a-card shadow="hover">
      <a-table :data-source="tenantList" :pagination="false">
        <a-table-column title="租户编号" align="center" data-index="tenantId" />
        <a-table-column title="联系人" align="center" data-index="contactUserName" />
        <a-table-column title="联系电话" align="center" data-index="contactPhone" />
        <a-table-column title="企业名称" align="center" data-index="companyName" />
        <a-table-column title="社会信用代码" align="center" data-index="licenseNumber" />
        <a-table-column title="过期时间" align="center" data-index="expireTime" width="180">
          <template #default="{ record }">
            <span>{{ parseTime(record.expireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </a-table-column>
        <a-table-column title="租户状态" align="center" data-index="status">
          <template #default="{ record }">
            <a-switch
              v-model:checked="record.status" checked-value="0" un-checked-value="1"
              @change="handleStatusChange(record)"
            />
          </template>
        </a-table-column>
        <a-table-column width="150" title="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-tooltip content="修改" placement="top">
              <a-button v-hasPermi="['system:tenant:edit']" link type="link" @click="handleUpdate(record)">
                修改
              </a-button>
            </a-tooltip>
            <a-tooltip content="同步套餐" placement="top">
              <a-button v-hasPermi="['system:tenant:edit']" link type="link" @click="handleSyncTenantPackage(record)">
                同步
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button v-hasPermi="['system:tenant:remove']" link type="link" @click="handleDelete(record)">
                删除
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>

      <div class="text-right mt-20px">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>
    <!-- 添加或修改租户对话框 -->
    <a-modal v-model:open="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <a-form ref="tenantFormRef" :model="form" :rules="rules" laba-width="80px">
        <a-form-item label="企业名称" name="companyName">
          <a-input v-model:value="form.companyName" placeholder="请输入企业名称" />
        </a-form-item>
        <a-form-item label="联系人" name="contactUserName">
          <a-input v-model:value="form.contactUserName" placeholder="请输入联系人" />
        </a-form-item>
        <a-form-item label="联系电话" name="contactPhone">
          <a-input v-model:value="form.contactPhone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item v-if="!form.id" label="用户名" name="username">
          <a-input v-model:value="form.username" placeholder="请输入系统用户名" maxlength="30" />
        </a-form-item>
        <a-form-item v-if="!form.id" label="用户密码" name="password">
          <a-input v-model:value="form.password" type="password" placeholder="请输入系统用户密码" maxlength="20" />
        </a-form-item>
        <a-form-item label="租户套餐" name="packageId">
          <a-select
            v-model:value="form.packageId" :disabled="!!form.tenantId" placeholder="请选择租户套餐" clearable
            style="width: 100%"
          >
            <a-select-option
              v-for="item in packageList" :key="item.packageId" :label="item.packageName"
              :value="item.packageId"
            >
              {{ item.packageName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="过期时间" name="expireTime">
          <a-date-picker
            v-model:value="form.expireTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择过期时间"
          />
        </a-form-item>
        <a-form-item label="用户数量" name="accountCount">
          <a-input v-model:value="form.accountCount" placeholder="请输入用户数量" />
        </a-form-item>
        <a-form-item label="绑定域名" name="domain">
          <a-input v-model:value="form.domain" placeholder="请输入绑定域名" />
        </a-form-item>
        <a-form-item label="企业地址" name="address">
          <a-input v-model:value="form.address" placeholder="请输入企业地址" />
        </a-form-item>
        <a-form-item label="企业代码" name="licenseNumber">
          <a-input v-model:value="form.licenseNumber" placeholder="请输入统一社会信用代码" />
        </a-form-item>
        <a-form-item label="企业简介" name="intro">
          <a-textarea v-model:value="form.intro" placeholder="请输入企业简介" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-input v-model:value="form.remark" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button :loading="buttonLoading" type="primary" @click="submitForm">
            确 定
          </a-button>
          <a-button @click="cancel">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
